import locale from '../locale/locale'
import { res } from '../demoData/tableFiled'
import { setCellValue, setCellFormat } from '../global/api'
import { modelHTML } from './constant'
import {
  replaceHtml,
  getObjType,
  mouseclickposition,
  luckysheetContainerFocus,
  coordinateToArray,
} from '../utils/util'

var time = 0
const _locale = locale()
const locale_border = _locale.border
const locale_toolbar = _locale.toolbar
const locale_button = _locale.button
const dvText = _locale.dataVerification
var l
var t
window.initCellDialog = function(data, type) {
  var postion = data
  var nowData
  setTimeout(function() {
    var left
    var top
    var right
    var height
    var isLeft
    var wid

    //得到浏览器的客户区宽高
    var docw = document.body.clientWidth
    var doch = document.body.clientHeight
    if ($('#luckysheet-table-dialog')) {
      $('#luckysheet-table-dialog').remove()
    }

    let content = `<div class="luckysheet-modal-dialog-slider box" id="luckysheet-table-dialog" style="width: 678px;
    height:355px;min-height:355px;max-height:100%;background: #fff;">
        <div class="box-item" style="border-bottom: none;margin: 12px 10px;font-size: 12px;">  
        <div id="data-dict-range" class="range" style="border: none;height: 30px;margin-bottom: 5px;">  
       
        <div style="display:inline-block;float:left">
          <span>项目名称</span>  
          <input id="tableName" class="formulaInputFocus" spellcheck="false" style="float:none;width: 150px;border: 1px solid #d4d4d4;outline:none">
        </div>
        <div style="display:inline-block;float:left;margin-left:10px">
          <span>项目编码</span>  
          <input id="tableCode" class="formulaInputFocus" spellcheck="false" style="float:none;width: 150px;border: 1px solid #d4d4d4;outline:none;">
        </div>
        <button id="luckysheet-table-dialog-confirm2" class="btn btn-primary noline" style="margin:0 10px 0 15px;background:rgba(76, 76, 76, 0.1);padding:0 5px;
        color: inherit;">${locale_button.get}</button>
        <button id="luckysheet-table-dialog-reset" class="btn btn-default" style="outline: none !important;padding:0 5px;font-size: 12px;">${locale_button.reset}</button>
    </div>
        <div style="position: relative;margin:0 auto;width:100%;height: 100%;overflow-y:auto;overflow-x:hidden;">
          <table id="Table" class="table-bordered" style="width:100%;border-collapse: collapse;
          margin-bottom: 12px;
      "></table>
      </div>
          
        </div>
    </div>`
    $('body')
      .first()
      .append(content)
    wid = $('#luckysheet-table-dialog').css('width')
    wid = parseFloat(wid.substring(0, wid.length - 2))
    if (type == 1) {
      left = $('#luckysheet-input-box').position().left
      top = $('#luckysheet-input-box').position().top
      height = $('#luckysheet-input-box').css('height')
      height = parseFloat(height.substring(0, height.length - 2))
      let rect = document
        .getElementById('luckysheet-input-box')
        .getBoundingClientRect()
      //得到dom元素的宽高，ie8-不支持rect.width,rect.height
      var basew = rect.right - rect.left
      var baseh = rect.bottom - rect.top
      //判断dom元素的左边空间大还是右边空间大
      var isleft = docw - rect.left
      //判断dom元素的上边空间大还是下面空间大
      var istop = doch - rect.bottom
      right = docw - rect.right
      if (docw - basew - rect.x >= wid) {
        isLeft = true
      } else {
        isLeft = false
      }
    } else {
      let obj = document
        .getElementById('luckysheet-cell-selected')
        .getBoundingClientRect()
      left = obj.left
      top = obj.top
      // right = obj.right;
      height = obj.height
      //判断dom元素的左边空间大还是右边空间大
      var isleft = docw - obj.left
      var basew = obj.right - obj.left
      right = docw - obj.right
      if (docw - basew - obj.x >= wid) {
        isLeft = true
      } else {
        isLeft = false
      }
    }

    var data = [
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        salary: '$3,120',
        start_date: '2011/04/25',
        office: 'Edinburgh',
        extn: '5421',
      },
      {
        name: 'Garrett Winters',
        position: 'Director',
        salary: '$5,300',
        start_date: '2011/07/25',
        office: 'Edinburgh',
        extn: '8422',
      },
    ]
    $(document).ready(function() {
      var tables = $('#Table').DataTable({
        // "data": data,
        // url: './demoData/testTableData.json',
        ajax: {
          type: 'GET',
          url: '/demoData/testTableData.json',
          dataSrc: '',
        },
        ordering: false,
        searching: false,
        select: true,
        // fixedColumns: true,
        // fixedHeader: true,
        columns: [
          // { "title": "序号", "class": "center" },
          // { "title": "项目名称",data: 'name', "class": "center" },
          // { "title": "项目编码",data: 'position', "class": "center" },
          // { "title": "Platform",data: 'salary', "class": "center" },
          // { "title": "Version", "class": "center",data: 'office' },
          // { "title": "Grade", "class": "center",data: 'extn' },
          { title: '项目名称', data: 'Name', class: 'center' },
          { title: '项目编码', data: 'Code', class: 'center' },
          { title: 'Platform', data: 'Type', class: 'center' },
          { title: 'Version', class: 'center', data: 'Type' },
          { title: 'Grade', class: 'center', data: 'Type' },
        ],
        language: {
          decimal: '',
          emptyTable: 'No data available in table',
          info: '共 _TOTAL_ 条记录',
          infoEmpty: 'Showing 0 to 0 of 0 entries',
          infoFiltered: '(filtered from _MAX_ total entries)',
          infoPostFix: '',
          thousands: ',',
          lengthMenu: '每页显示 _MENU_ 条',
          loadingRecords: 'Loading...',
          processing: 'Processing...',
          search: 'Search:',
          zeroRecords: 'No matching records found',
          paginate: {
            first: '11',
            last: 'Last',
            next: '>',
            previous: '<',
          },
          aria: {
            sortAscending: ': activate to sort column ascending',
            sortDescending: ': activate to sort column descending',
          },
        },
        // "aoColumnDefs": [{
        // 　　　　"render": function (data, type) {
        // 　　　　　　return "<div align='center'><input type=\"radio\"  name=\"ckb-jobid\" value=" + data + "></div>";
        // 　　　　}, "aTargets": 0 //第一列
        // 　　} ],
      })
      var p = $('#luckysheet-table-dialog')
      // var offset = p.offset()
      // top = top == '-10000px' ? 0 : top;
      top = top == '-10000' ? 0 : top
      var cWidth =
        document.body.clientWidth || document.documentElement.clientWidth //页面可视区域宽度
      var iWidth = window.innerWidth //浏览器窗口大小
      let a = iWidth - cWidth
      if (isLeft) {
        p.css({
          top: top + height + 4 + 'px',
          left: left + 'px',
        })
      } else {
        p.css({
          top: top + height + 4 + 'px',
          right: right + a + 'px',
        })
      }
      // $('#luckysheet-table-dialog').show()
      //   let $t = $('#luckysheet-table-dialog')
      //   .find('.luckysheet-modal-dialog-content')
      //   .css('min-width', 700)
      //   .end(),
      //   myh = $t.outerHeight(),
      //   myw = $t.outerWidth()
      // let winw = $(window).width(),
      //   winh = $(window).height()
      // let scrollLeft = $(document).scrollLeft(),
      //   scrollTop = $(document).scrollTop()
      // $('#luckysheet-table-dialog').css({
      //   left: (winw + scrollLeft - myw) / 2,
      //   top: (winh + scrollTop - myh) / 3,
      // })
      $('#Table tbody').on('click', 'tr', function() {
        // event.stopPropagation();
        nowData = tables.rows(this).data()[0]
        window.luckysheet.exitEditMode()
        l = postion.r
        t = postion.c
        setTimeout(() => {
          setCellValue(postion.r, postion.c, {
            m: nowData.Name,
            v: nowData.Name,
          })
          $('#luckysheet-table-dialog').hide()
        }, 100)
      })
      $('#luckysheet-table-dialog-confirm').on('click', function() {
        window.luckysheet.exitEditMode()
        event.stopPropagation()
        $('#luckysheet-table-dialog').hide()
        setTimeout(() => {
          setCellValue(postion.r, postion.c, {
            m: nowData.Name,
            v: nowData.Name,
          })
        }, 100)
      })
      //table搜索功能
      $('#luckysheet-table-dialog-confirm2').on('click', function() {
        getTableData()
      })
      //table重置搜索条件
      $('#luckysheet-table-dialog-reset').on('click', function() {
        $('#tableName').val('')
        $('#tableCode').val('')
        getTableData()
      })

      //灰色弹窗mask
      // $('#luckysheet-modal-dialog-mask').show()
      // $('#luckysheet-table-dialog').show()

      // $('#dataconfigmouseFnc').on('click', function () {
      //   event.stopPropagation();
      // });
      // $('#luckysheet-modal-dialog-protection-close').on('click', function () {

      //   closeProtectionModal();
      // });
      $('body .luckysheet-grid-window').on('click', function() {
        closeProtectionModal()
      })

      time++
    }, 500)
  })
}

//查询表格数据
function getTableData() {
  let name = $('#tableName').val()
  let code = $('#tableCode').val()
  $.ajax({
    url: './demoData/testTableData.json',
    // url: './demoData/testTableData.json?name='+name+'&code='+code,
    type: 'get',
    dataTyoe: 'json',
    success: (res) => {
      data = res.data
      // 清空DataTables数据
      // $("#Table").dataTable().fnClearTable();
      // // 销毁旧的DataTables对象，以便初始化新的DataTables
      // $("#Table").dataTable().fnDestroy();
      // // 动态生成tr，并渲染数据
      // setValue(JSON.parse(jsonStr));
      // // 照常初始化DataTables
      // var table = $('#datatable-buttons8').DataTable({
      //     // DataTables的配置属性：http://www.datatables.club/reference/option/
      //     lengthChange: false,
      //     buttons:  ['copy', 'excel', 'pdf']
      // });
      // table.buttons().container()
      //     .appendTo('#datatable-buttons8_wrapper .col-md-6:eq(0)');

      // window.luckysheet.sheetmanage.setSheetDataByJson(res, options)
    },
  })
}

function closeProtectionModal() {
  $('#luckysheet-table-dialog').hide()
}

// setValue根据clsName的不同进入setTableValue
function setTableValue(clsName, jsonStr) {
  var table = $('.' + clsName + ' tbody')
  // 在此之前可以清空所有旧的tr
  table.empty()
  var data = jsonStr[clsName]
  for (var i = 0; i < data.length; i++) {
    // 生成tr
    var $trTemp = $('<tr></tr>')
    var obj = data[i]
    var keys = Object.keys(obj)
    var attrCount = keys.length
    for (var j = 0; j < attrCount; j++) {
      // 生成td
      $trTemp.append('<td>' + obj[keys[j]] + '</td>')
    }
    $trTemp.appendTo(table)
  }
}
